import { defineComponent, ref, reactive, onMounted } from 'vue'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElIcon,
  ElMessage,
  ElMessageBox,
  ElSpace,
  ElLink
} from 'element-plus'
import { Plus, EditPen, Delete } from '@element-plus/icons-vue'
import { useStore } from 'vuex'

import type { ManholeItemType, ManholeStateType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import styles from './../index.module.scss'
import AliIcon from '~/components/AliIocn'
import ExportExcel from '~/components/ExportExcel'
import ImportExcel from './ImportExcel'
import HardwareOptions from './option'

export default defineComponent(function Hardware() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ManholeItemType>({})
  const userState = useVuexGetters('user', ['permission']) // 按钮权限
  const manholeState = useVuexGetters('manhole', ['manholeModelOpt'])
  const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
  const state = reactive({
    importVisible: false, // 导入 弹窗是否显示
    exportVisible: false, // 导出 弹窗是否显示
    modalVisible: false,
    record: {},
    type: 'read'
  })
  const columns: TableColumnProps<ManholeItemType>[] = [
    {
      label: '设备名称',
      prop: 'name',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      sortable: true,
      disabled: true, // 不可编辑
      showOverflowTooltip: true
    },
    {
      label: '设备编号',
      prop: 'code',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '所属区域',
      prop: 'workAreaName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '设备型号',
      prop: 'modelName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '设备品牌',
      prop: 'brand',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '厂家',
      prop: 'manufacturer',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '投运状态',
      prop: 'isDeliver',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true,
      render: (_, value) => {
        return (
          <>
            {value === 1 && '已投运'}
            {value === 0 && '未投运'}
          </>
        )
      }
    },
    {
      label: '更新人',
      prop: 'updateUserName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '更新日期',
      prop: 'updateTime',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '所属街道',
      prop: 'streetName',
      minWidth: 180,
      sortable: true,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: '投运日期',
      prop: 'deliverDate',
      minWidth: 180,
      sortable: true,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: 'SIM卡号',
      prop: 'simNode',
      minWidth: 180,
      sortable: true,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: '设备地址',
      prop: 'address',
      minWidth: 180,
      sortable: true,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      fixed: 'right',
      align: 'center',
      unFixed: true,
      disabled: true,
      minWidth: 220,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('asset_lamp_control_view') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情
            </ElLink>
          )}
          {userState.permission.value.has('asset_lamp_control_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp;编辑
            </ElLink>
          )}
          {userState.permission.value.has('asset_lamp_control_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空/下拉框值变 搜索
  const clearSearchTable = () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  // 新增/编辑
  const handleChangeOptionsModal = (type: ManholeStateType['type'], record?: ManholeItemType) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }
  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: ManholeItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        handleDeleteSelectedData(params)
      })
      .catch(() => {})
  }
  // 执行删除操作
  const handleDeleteSelectedData = async (ids: string) => {
    await store
      .dispatch('manhole/ManholeRemovePost', {
        ids
      })
      .then((res: { code: number }) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }
  // 导入
  const handleChangeImportModal = () => {
    state.importVisible = !state.importVisible
    proSaasTableRef.value?.toSearch() // 刷新
  }
  // 导出
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }
  onMounted(async () => {
    //  井盖型号
    await store.dispatch('manhole/ManholeModelGet')
    // 所属区域
    await store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser')
  })
  return () => {
    if (state.modalVisible) {
      return (
        <HardwareOptions
          record={state.record}
          type={state.type}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }
    return (
      <ElCard>
        <ProSaasTable<ManholeItemType>
          tableId="ManholeTableId"
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          hasSelection
          dispatchType="manhole/ManholeListGet"
          searchFormProps={{
            model: formValues
          }}
          headerTitle={
            <>
              {userState.permission.value.has('asset_lamp_control_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {userState.permission.value.has('asset_lamp_control_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <ElIcon>
                    <Delete />
                  </ElIcon>
                  &nbsp; 删除
                </ElButton>
              )}
              {userState.permission.value.has('asset_lamp_control_import') && (
                <ElButton type="primary" onClick={() => handleChangeImportModal()}>
                  <AliIcon type="icon-daoru" />
                  &nbsp; 导入
                </ElButton>
              )}
              {userState.permission.value.has('asset_lamp_control_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="name" prop="name">
              <ElInput
                v-model={formValues.name}
                {...{ maxlength: 30 }}
                placeholder="设备名称/设备编号"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="modelId" prop="modelId">
              <ElSelect
                v-model={formValues.modelId}
                placeholder="型号"
                clearable
                onChange={clearSearchTable}
              >
                {manholeState.manholeModelOpt.value?.map((item: any) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="workAreaId" prop="workAreaId">
              <ElSelect
                v-model={formValues.workAreaId}
                placeholder="所属区域"
                clearable
                onChange={clearSearchTable}
              >
                {assetWorkAreaState.workAreaSelectList?.value?.map((item: any) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>
          ]}
        />
        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="manhole/ManholeExportGet"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}
        {/* 导入 */}
        {state.importVisible && <ImportExcel doCancel={handleChangeImportModal} />}
      </ElCard>
    )
  }
})
